package sys_dept_dao

import (
	"database/sql"
	"gf-admin/app/pojo/sys/sys_dept"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
)


//获取列表数据
func GetList(searchParams *sys_dept.SearchParams) ([]*sys_dept.Dept, error) {
	model := g.DB().Table(sys_dept.Table)
	if searchParams.DeptName != "" {
		model.Where("dept_name like ?", "%"+searchParams.DeptName+"%")
	}

	if searchParams.Status != "" {
		model.Where("status", searchParams.Status)
	}
	depts := ([]*sys_dept.Dept)(nil)
	if err := model.Structs(&depts); err != nil {
		return nil, err
	}

	for _, v := range depts {
		if v.Children == nil {
			v.Children = []interface{}{}
		}

	}

	return depts, nil
}

//添加
func AddDept(data *sys_dept.AddParams) (sql.Result, error) {
	data.DelFlag = "0"
	data.CreateBy = ""
	data.CreateTime = gtime.Now()
	return sys_dept.Model.Data(data).Insert()
}

//编辑
func EditDept(data *sys_dept.EditParams) error {
	data.UpdateBy = ""
	data.UpdateTime = gtime.Now()

	if _, err := sys_dept.Model.Where("dept_id", data.DeptID).Data(data).Update(); err != nil {
		return err
	}
	return nil
}

//删除失败
func DelDept(id int64) error {

	ids, _ := GetChilderenIds(id)
	_, err := sys_dept.Model.Where("dept_id IN(?)", ids).Delete()
	if err != nil {
		return gerror.New("删除失败")
	}
	return nil
}

//根据部门id获取部门信息
func GetDeptById(id uint64) (*sys_dept.Dept, error) {

	dept := (*sys_dept.Dept)(nil)

	if err := sys_dept.Model.Where("dept_id", id).Struct(&dept); err != nil {
		return nil, err
	} else {
		return dept, nil
	}

}

/**
获取排除节点
*/
func Exclude(id int64) ([]*sys_dept.Dept, error) {
	ids, err := GetChilderenIds(id)
	if err != nil {
		return nil, err
	}

	model := g.DB().Table(sys_dept.Table)
	if len(ids) > 0 {
		model.Where("dept_id  NOT IN(?)", ids)
	}

	depts := ([]*sys_dept.Dept)(nil)
	if err := model.Structs(&depts); err != nil {
		return nil, err
	}

	for _, v := range depts {
		if v.Children == nil {
			v.Children = []interface{}{}
		}

	}
	return depts, nil
}

/**
根据id获取子孙节点id集合包含本身
*/
func GetChilderenIds(id int64) ([]int64, error) {

	list, err := GetChildrenById(id)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return []int64{}, nil
	}
	var newResult []int64
	for _, v := range list {
		newResult = append(newResult, v.DeptId)
	}

	return newResult, nil
}

/**
根据id获取所有子孙节点包含本身
*/
func GetChildrenById(id int64) ([]*sys_dept.Entity, error) {
	depts, err := sys_dept.Model.All()
	if err != nil {
		return nil, err
	}
	result := recursion(id, depts, true)
	return result, nil
}

/**
根据id获取所有子孙元素

hasroot true - 包含自身  false - 不含自身
*/
func recursion(id int64, depts []*sys_dept.Entity, hasRoot bool) (result []*sys_dept.Entity) {
	for _, v := range depts {
		if hasRoot == true && v.DeptId == id {
			result = append(result, v)
		}
		if v.ParentId == id {
			data := recursion(v.DeptId, depts, false)
			result = append(result, v)
			result = append(result, data...)
		}
	}

	return
}
